package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {


    @Autowired
    private OrderMapper orderMapper;


    @Scheduled(cron = "0 * * * * ?")//一分钟处理一次
    public void processTimeoutOrder(){
        log.info("定时处理未付款的订单：{}",LocalDateTime.now());
        //定义订单未付款超时应处于的状态
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> list= orderMapper.getByStatusAndTimeLT(status,time);
        if(list != null && list.size()>0){
            for (Orders orders : list) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时，自动取消");
                orderMapper.update(orders);
            }
        }
    }
    @Scheduled(cron = "0 1 * * * ?")//每天凌晨一点处理
    public void processDeliveryOrder(){
        //定义处于派送中超时的订单状态
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> list = orderMapper.getByStatusAndTimeLT(status, time);
        if(list != null && list.size()>0){
            for (Orders orders : list) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
